package com.gjx.clock

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.SortedList
import com.gjx.clock.entity.NormalAlarmClock
import com.gjx.clock.entity.RestAlarmClock
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.thread


class ClockViewModel : ViewModel() {
    private val restClockDao = AppDatabase.getDatabase(ClockApplication.context).restClockDao()
    private val normalClockDao = AppDatabase.getDatabase(ClockApplication.context).normalClockDao()
    private val clLiveData = MutableLiveData<String>()
    val restClockList = ArrayList<RestAlarmClock>()

    //    val normalClockList = ArrayList<NormalAlarmClock>()
    // 这里替换为排序的列表
    val normalClockList = SortedList<NormalAlarmClock>(NormalAlarmClock::class.java,
        object : SortedList.Callback<NormalAlarmClock>() {
            // id
            override fun areItemsTheSame(
                item1: NormalAlarmClock?,
                item2: NormalAlarmClock?
            ): Boolean {
                return item1?.id == item2?.id
            }

            override fun onMoved(fromPosition: Int, toPosition: Int) {
            }

            override fun onChanged(position: Int, count: Int) {
            }

            override fun onInserted(position: Int, count: Int) {
            }

            override fun onRemoved(position: Int, count: Int) {
            }

            // 和视觉表现有关
            override fun areContentsTheSame(
                oldItem: NormalAlarmClock?,
                newItem: NormalAlarmClock?
            ): Boolean {
                return oldItem == newItem
            }

            override fun compare(o1: NormalAlarmClock?, o2: NormalAlarmClock?): Int {
                return o1!!.compareTo(o2!!)
            }

        })

    fun insertClock(clock: NormalAlarmClock) {
        val id = normalClockDao.insertClock(clock)
        clock.id = id
        normalClockList.add(clock)
    }

    fun updateClock(clock: NormalAlarmClock) {
        normalClockDao.updateClock(clock)
    }

    fun deleteClock(clock: NormalAlarmClock) {
        normalClockDao.deleteClock(clock)
        normalClockList.remove(clock)
    }

    fun getClockById(id: Long) = normalClockDao.getClockById(id)


    fun insertClock(clock: RestAlarmClock) {
        val id = restClockDao.insertClock(clock)
        // 这里clock的id还是0，需要根据返回的id修改一下
        clock.id = id
        restClockList.add(clock)
    }

    fun updateClock(clock: RestAlarmClock) {
        restClockDao.updateClock(clock)
    }

    fun deleteClock(clock: RestAlarmClock) {
        restClockDao.deleteClock(clock)
        restClockList.remove(clock)
    }


    fun loadRestClocks() {
        restClockList.clear()
        restClockList.addAll(restClockDao.loadAllClocks())
    }

    fun loadNormalClocks() {
        normalClockList.clear()
        normalClockList.addAll(normalClockDao.loadAllClocks())
    }


}